<template>
  <el-icon :size="20" title="菜单搜索" @click="handleSearch">
    <Search />
  </el-icon>
  <transition name="slide-fade">
    <el-select
      v-show="show"
      ref="selectRef"
      v-model="keyword"
      filterable
      remote
      placeholder="Search"
      :remote-method="remoteMethod"
      :class="{ show: show }"
      @change="handleChange"
      @blur="show = false"
    >
      <el-option
        v-for="item in routes"
        :key="item.path"
        :label="item.title.join(' -> ')"
        :value="item.path"
      />
    </el-select>
  </transition>
</template>

<script setup>
import { Search } from 'lucide-vue-next'

import { transformRoutesForSearch } from '~utils/util'

const props =  defineProps({
  routesData: {
    type: Object,
    default: () => ({})
  }
})
const emits = defineEmits(['change'])

const show = ref(false)
const routes = ref([])
const keyword = ref('')
const searchData = transformRoutesForSearch(props.routesData)
const selectRef = ref(null)
const remoteMethod = (query) => {
  if (query) {
    routes.value = searchData.filter((item) => {
      return item.title.toString().includes(query)
    })
  } else {
    routes.value = []
  }
}

const handleSearch = () => {
  show.value = true
  nextTick(() => {
    selectRef.value.focus()
  })
}

const handleChange = (val) => {
  keyword.value = ''
  emits('change', val)
}
</script>

<style lang="scss" scoped>
.el-icon {
  cursor: pointer;
}

.el-select {
  width: 150px;
}

.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from {
  transform: translateX(20px);
  opacity: 0;
}

.slide-fade-leave-to {
  transform: translateX(20px);
  opacity: 0;
}
</style>
